//
//  AppDelegate.m
//  TTAddressBook
//
//  Created by hubin on 11-12-8.
//  Copyright (c) 2011年 __MyCompanyName__. All rights reserved.
//

#import "AppDelegate.h"
#import "CommTools.h"
#import "firstViewController.h"
#import "UIPhoneViewController.h"
#import "UIContactsViewController.h"
#import "SettingViewController.h"
#import "messageViewController.h"
#import "AccountSettingViewController.h"
#import "SettingConstants.h"

#import <EventKit/EventKit.h>
#import <EventKitUI/EventKitUI.h>

@implementation AppDelegate

@synthesize window = _window;
@synthesize isCounting;
@synthesize ntime;

@synthesize navigationController;
@synthesize waitingView;
@synthesize activityView;
@synthesize labelForActivity;
@synthesize MainTabbarViewController;
@synthesize navSetting;
@synthesize curAlertView;



- (void)dealloc
{
    [_window release];
    [labelForActivity release];
    [MainTabbarViewController release];
    [navSetting release];
    [lauchViewCtr release];
    [super dealloc];
}


#pragma mark UITableViewDelegate protocol conformance


- (void) ShowMainView
{
    self.MainTabbarViewController = [[[UITabBarController alloc] init] autorelease];
    UICalendarViewController  * uCalendar = [[UICalendarViewController alloc] initWithNibName:@"UICalendarViewController" bundle:nil];
    uCalendar.tabBarItem=[[UITabBarItem alloc] init];
    uCalendar.tabBarItem.tag  = 0;
    [uCalendar.tabBarItem setImage:[UIImage imageNamed:@"t1.png"]];
    UINavigationController * navController=[[UINavigationController alloc] initWithRootViewController:uCalendar];
    uCalendar.tabBarItem.title = @"日程";
    navController.navigationBar.tintColor = [UIColor colorWithRed:globalRed/255 green:globalGreen blue:globalBlue/255 alpha:1.0];
    
    messageViewController* uSms = [[messageViewController alloc] init];
    uSms.tabBarItem=[[UITabBarItem alloc] init];
    uSms.tabBarItem.tag  = 3;
    [uSms.tabBarItem setImage:[UIImage imageNamed:@"t2.png"]];
    UINavigationController* navSms = [[UINavigationController alloc] initWithRootViewController:uSms];
    navSms.navigationBar.tintColor =  [UIColor colorWithRed:globalRed/255 green:globalGreen blue:globalBlue/255 alpha:1.0];//[UIColor colorWithRed:130.0/255 green:0.0 blue:30.0/255 alpha:1.0];
    uSms.tabBarItem.title = @"消息";
    
    UIContactsViewController  * uContacts = [[UIContactsViewController alloc] initWithNibName:@"UIContactsViewController" bundle:nil];
    uContacts.tabBarItem=[[UITabBarItem alloc] init];
    uContacts.tabBarItem.tag  = 2;
    [uContacts.tabBarItem setImage:[UIImage imageNamed:@"t3.png"]];
    UINavigationController * navContacts=[[UINavigationController alloc] initWithRootViewController:uContacts];
    navContacts.navigationBar.tintColor =  [UIColor colorWithRed:globalRed/255 green:globalGreen blue:globalBlue/255 alpha:1.0];//[UIColor colorWithRed:130.0/255 green:0.0 blue:30.0/255 alpha:1.0];
    uContacts.tabBarItem.title = @"社区";
    
    //设置页面
    SettingViewController* uSet = [[SettingViewController alloc] initWithNibName: @"SettingViewController" bundle:nil];
    uSet.tabBarItem=[[UITabBarItem alloc] init];
    uSet.tabBarItem.tag  = 3;
    uSet.tabBarItem.title = @"设置";
    [uSet.tabBarItem setImage:[UIImage imageNamed:@"t4.png"]];
    navSetting = [[UINavigationController alloc] initWithRootViewController: uSet];
    navSetting.navigationBar.tintColor =  [UIColor colorWithRed:globalRed/255 green:globalGreen blue:globalBlue/255 alpha:1.0];//[UIColor colorWithRed:130.0/255 green:0.0 blue:30.0/255 alpha:1.0];
    NSArray* controllers = [NSArray arrayWithObjects:navController,navSms,navContacts,navSetting, nil];
    MainTabbarViewController.viewControllers = controllers;    
    MainTabbarViewController.selectedIndex = 0;
    [self.window addSubview:MainTabbarViewController.view];
    [uContacts release];
    [navContacts release];
    [navSms release];
    [uSms release];
    [uSet release];
}


- (void)gotoAccountSetting
{
    [theAppDelegate ShowMainView];
    theAppDelegate.MainTabbarViewController.selectedIndex = 3;
    
    AccountSettingViewController *accountSettingView = [[AccountSettingViewController alloc] initWithNibName:@"AccountSettingViewController" bundle:nil];
    [theAppDelegate.navSetting pushViewController:accountSettingView animated:NO];
    [accountSettingView release];
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    globalRed = 130.0;
    globalGreen=0.0;
    globalBlue = 30.0;
    // Override point for customization after application launch.
    //设置网络状态等待 全屏显示不需要
    //[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
    //隐藏系统状态栏
//    [[UIApplication sharedApplication] setStatusBarHidden:YES withAnimation:UIStatusBarAnimationSlide];
    
    self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
    
    //启动界面logo
    UIImageView *logoView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];
    //logoView.image = [UIImage imageNamed:@"startlogo.png"];
    [self.window addSubview:logoView];
    [logoView release];
    
    
    //等待框 added by wangj 2011.12.20
    int screenWidth = 320;
    int screenHeight = 480;
    int width = 320;
    int height = 100;
    waitingView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, screenWidth, screenHeight)];
    [waitingView setHidden:YES];
    [waitingView setAlpha:0.7];
    [self.window addSubview:waitingView];
    
    CGRect frameRect = CGRectMake( (screenWidth - width) / 2, (screenHeight - height) / 2, width, height);
    UIView *view = [[UIView alloc]initWithFrame:frameRect];
    //	[waitingView.layer setMasksToBounds:YES]; 
    //	[waitingView.layer setCornerRadius:5];
    //	[view setHidden:YES];
	[view setBackgroundColor:[UIColor blackColor]];
	[view setAlpha:0.8];
    [waitingView addSubview:view];
	
    CGRect activityRect = CGRectMake( (width - 24) / 2, (height - 24) / 5, 24, 24);
	activityView = [[UIActivityIndicatorView alloc] initWithFrame:activityRect];
	[view addSubview:activityView];
	[activityView release];
	
	labelForActivity = [[UILabel alloc] initWithFrame:CGRectMake( 0, 24 + ( height - 24 - 15 ) / 2, width, 15)];
	[labelForActivity setBackgroundColor:[UIColor clearColor]];
	[labelForActivity setText:@"加载中..."];
	[labelForActivity setTextAlignment:UITextAlignmentCenter];
    labelForActivity.font = [UIFont systemFontOfSize:14];
	[labelForActivity setTextColor:[UIColor whiteColor]];
	[view addSubview:labelForActivity];
    [self.window sendSubviewToBack:waitingView];
    
    [view release];
    [waitingView release];    //added end
    
    //仅仅在首次安装后第一次启动会显示,以后再次启动不会显示
//    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
//    NSString *documentsDirectory = [paths objectAtIndex:0];
//    NSString *path = [documentsDirectory stringByAppendingPathComponent:@"a"];
//	NSFileManager *fileManager = [NSFileManager defaultManager];
	NSString * strUser =   [[MyClass getInstance] getStoredName];
    BOOL isExit=NO;    
    if ([strUser length]>0)
    {
        NSDictionary * ret = [[MyClass getInstance] validatedUser];
        NSString * msg = [NSString stringWithFormat:@"%@", [ret objectForKey:@"code"]];
        if ([msg intValue] == 0) {
            isExit = YES;
        }

    }

    if ( !isExit )   //如果token不存在的话，表示还未激活，要显示首次激活页面
    {      
        firstViewController* lauchview = [[firstViewController alloc] initWithNibName:@"firstViewController" bundle:nil];
        lauchViewCtr = [[UINavigationController alloc] initWithRootViewController:lauchview];
        //[[firstViewController alloc] initWithNibName:@"firstViewController" bundle:nil];
        
        [self.window addSubview:lauchViewCtr.view];
        [self.window makeKeyAndVisible];
        
        //创建lauch.dat文件，下次执行时跳过
       // [fileManager createFileAtPath:path contents:nil attributes:nil];
        
        //[lauchViewCtr release];
        return YES;
    }
    
    [self ShowMainView];
    
    [self.window makeKeyAndVisible];
    
    
    return YES;
}
    

- (void)applicationWillResignActive:(UIApplication *)application
{
    //删除掉当前提示框
    [self.curAlertView dismissWithClickedButtonIndex:0 animated:NO];
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{

}

- (void)applicationWillEnterForeground:(UIApplication *)application
{

}


- (void)applicationWillTerminate:(UIApplication *)application
{

}

- (void)OnLoginView:(BOOL)bLogin
{
    [self ShowMainView];
}

#pragma mark - UITabBarDelegate
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
    NSMutableString  *tokenStr = [[NSMutableString alloc] initWithFormat:@"%@", deviceToken];
    NSDictionary * ret = [[MyClass getInstance] sendApnsToken: tokenStr];
    NSString * msg = [NSString stringWithFormat:@"%@", [ret objectForKey:@"code"]];
    if ([msg intValue] == 0) {
        
    }
    NSLog(@"%@" ,tokenStr);
} 

// Provide a user explanation for when the registration fails 推送注册失败返回这里
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error 
{
	//NSString *status = [NSString stringWithFormat:@"%c\nRegistration failed.\n\nError: %@", [self pushStatus], [error localizedDescription]];
    NSLog(@"Error in registration. Error: %@", error); 
}

// 收到推送
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
	NSString *status = [NSString stringWithFormat:@"Notification received:\n%@",[userInfo description]];
    NSLog(@"%@",status);//推送内容
    
    [UIApplication sharedApplication].applicationIconBadgeNumber=0;
    //[self performSelector:@selector(showString:) withObject:userInfo afterDelay:1.0f];	
}
#pragma mark - 主动获取信息
- (void)applicationDidBecomeActive:(UIApplication *)application
{
    //后台到前台 需要执行的代码段 更新数据
    
    //如果是第一次启动,保存本地状态为关闭,　获取token

    {
        [[UIApplication sharedApplication] registerForRemoteNotificationTypes:7];
    }
//    NSString * strUser =   [[MyClass getInstance] getStoredName]; 
//    if ([strUser length]>0)
//    {
//        NSDictionary * ret = [[MyClass getInstance] validatedUser];
//        NSString * msg = [NSString stringWithFormat:@"%@", [ret objectForKey:@"code"]];
//        if ([msg intValue] == 0) {
//            [[NSNotificationCenter defaultCenter] postNotificationName:@"baohebaoApplogin" object:nil userInfo:nil];
//        }
//        
//    }
    
    [UIApplication sharedApplication].applicationIconBadgeNumber=0;
}
- (void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item
{
    if ( item.tag == 3 )    //个人中心
    {
        [item setImage:[UIImage imageNamed:kSettingLogoOnPng]];
    }
}
- (void)showActivityView:(BOOL)isShow text:(NSString *)textShowed
{
    if ( isShow )
    {
        if ( textShowed != nil )
        {
            labelForActivity.text = textShowed;
        }
        
        if ( ![activityView isAnimating] )
        {
            [waitingView setHidden:NO];
            [activityView startAnimating];
            [self.window bringSubviewToFront:waitingView];
        }
    }
    else
    {
        [waitingView setHidden:YES];
        [activityView stopAnimating];
        [self.window sendSubviewToBack:waitingView];
    }
}
@end
